package com.csxy.hxl.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.hxl.entity.EduSubject;
import com.csxy.hxl.entity.excel.SubjectData;
import com.csxy.hxl.entity.vo.OneSubject;
import com.csxy.hxl.entity.vo.TwoSubject;
import com.csxy.hxl.exception.MyException;
import com.csxy.hxl.listener.SubjectExcelListener;
import com.csxy.hxl.mapper.EduSubjectMapper;
import com.csxy.hxl.service.EduSubjectService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjectsList = baseMapper.selectList(wrapperOne);

        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> twoSubjectsList = baseMapper.selectList(wrapperTwo);

        List<OneSubject> finalSubjectList = new ArrayList<>();

        for (int i = 0; i < oneSubjectsList.size(); i++) {
            EduSubject oSubject = oneSubjectsList.get(i);
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(oSubject,oneSubject);
            finalSubjectList.add(oneSubject);

            ArrayList<TwoSubject> finalTwoSubjects = new ArrayList<>();

            for (int j = 0; j < twoSubjectsList.size(); j++) {
                EduSubject tSubject = twoSubjectsList.get(j);
                if(tSubject.getParentId().equals(oSubject.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(tSubject,twoSubject);
                    finalTwoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(finalTwoSubjects);

        }
        return finalSubjectList;
    }

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            InputStream is = file.getInputStream();
            EasyExcel.read(is, SubjectData.class,(ReadListener) new SubjectExcelListener(eduSubjectService))
                    .sheet().doRead();
        } catch (Exception e) {
            throw new MyException(20001, "excel文件读取异常！");
        }

    }
}
